package com.oa.tools.jobs;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.oa.tools.dao.OAFlowInstanceDAO;
import com.oa.tools.entity.OAFlowInstanceWithBLOBs;
import com.oa.tools.utils.MailUtil;
import com.oa.tools.utils.SysConfig;
import com.oa.tools.utils.http.EKPRequestClient;

import tk.mybatis.mapper.entity.Example;


/*@Configuration
@EnableScheduling
@Transactional*/
public class MyJob
{
  private long lastestDateMill = System.currentTimeMillis() - 1000L*60*60*3;
  
  @Autowired
  OAFlowInstanceDAO oAFlowInstanceDAO;

  //@Scheduled(cron="0 0/10 * * * ?")//10分钟
  public void exec() {
    try { createList(true);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public String createList(boolean notice) throws Exception
  {
    long lastestDateMill_tmp = this.lastestDateMill;
    this.lastestDateMill = System.currentTimeMillis();

    StringBuilder sb = new StringBuilder();
    Example example = new Example(OAFlowInstanceWithBLOBs.class);
    example.createCriteria().andEqualTo("doc_status", "20").andLike("doc_subject", "%入职办理%").andGreaterThan("DOC_CREATE_TIME", new Date(lastestDateMill_tmp));
    
    List<OAFlowInstanceWithBLOBs> objs = this.oAFlowInstanceDAO.selectByExample(example);
//    List<OAFlowInstanceWithBLOBs> objs = this.oAFlowInstanceDAO.selectByTime(new Date(lastestDateMill_tmp));
    if ((objs == null) || (objs.size() == 0)) {
    	sb.append("没有找到新入职员工信息");
    }else {
    	 for (OAFlowInstanceWithBLOBs obj : objs) {
    	      sb.append(createOne(obj,false,notice));
    	      sb.append("\r\n---------------------------------------------");
    	    }
    }
    return sb.toString();
  }

  public long getLastestDateMill() {
    return this.lastestDateMill;
  }

  public void setLastestDateMill(long lastestDateMill) {
	this.lastestDateMill = lastestDateMill;
  }

public String createOne(OAFlowInstanceWithBLOBs obj,boolean force,boolean notice) throws Exception {
    String xmlStr = obj.getExtendDataXml();
    System.out.println(xmlStr);

    Object[] result = EKPRequestClient.createNewStaffAccountCore(xmlStr,obj.getFdId(),null);

    if(result==null) {
    	return obj.getFdId()+"流程已处理:\r\n"+xmlStr;
    }
    
    obj.setExtendDataXml((String) result[0]);
    this.oAFlowInstanceDAO.updateByPrimaryKeySelective(obj);//.updateByPrimaryKeyWithBLOBs(obj);//

    String content = new StringBuilder().append("<pre><font color='red'>")
    		.append(result[1].toString().replace("<", "&lt;").replace(">", "&gt;").replaceAll("\\s+", ""))
    		.append("</pre><pre>").toString();
  
    if(notice) {
    	
    	String [] receiveMailAccounts = SysConfig.getSysArray("邮箱管理员接收邮箱");
    	MailUtil.sendMail(receiveMailAccounts, "工作邮箱和OA账号创建成功", new StringBuilder().append("创建邮箱和OA账号成功日志如下：\r\n").append(content).toString());
    }

    return content;
  }
}